package com.rf.sys.utils;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import com.rf.sys.model.User;

public class PasswordHelper {
	private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private static String algorithmName = "md5";
	private static int hashIterations = 2;

	public static User encryptPassword(User user) {
		String salt = "";
		if(user.getCredentialsSalt() != null && !user.getCredentialsSalt().equals("")){
			salt = user.getCredentialsSalt();
		}else{
			salt = randomNumberGenerator.nextBytes().toHex();
		}
		user.setCredentialsSalt(salt);
		String newPassword = new SimpleHash(algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getAccountName()+salt), hashIterations).toHex();
		user.setPassword(newPassword);
		return user;
	}
	public static void main(String[] args) {
		PasswordHelper passwordHelper = new PasswordHelper();
		User user = new User();
		user.setDescription("3434");
		user.setAccountName("root");
		user.setPassword("111111");
		user.setCredentialsSalt("4157c3feef4a6ed91b2c28cf4392f2d1");
		user = passwordHelper.encryptPassword(user);
		System.out.println("==password=="+user.getPassword()+"==========="+user.getDescription());
	}
}
